<template>
  <div class="view-content">
    <table-form
      ref="table"
      :index="false"
      :model="searchForm"
      :columns="columns"
      :load="load"
      :menus="menus"
      :page="true"
      @event="tableEvent"
    >
      <el-row :gutter="10">
        <el-col :span="24">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item :span="6" label="车牌号/证件号" prop="num">
                <el-input v-model="searchForm.num" placeholder="请输入车牌号/证件号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :span="6" label="布控类型" prop="type">
                <el-select v-model="searchForm.type" placeholder="请选择布控类型" @change="changeType">
                  <el-option v-for="(k,v) in typeList" :key="v" :value="v" :label="k" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :span="6" label="开始时间" prop="startTime">
                <el-date-picker
                  placeholder="开始时间"
                  type="datetime"
                  v-model="searchForm.startTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width:100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :span="6" label="结束时间" prop="endTime">
                <el-date-picker
                  placeholder="开始时间"
                  type="datetime"
                  v-model="searchForm.endTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width:100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item :span="6" label="处置措施" prop="action">
                <el-select v-model="searchForm.action">
                  <el-option v-for="(t,i) in store.state.dictionary.action" :key="'action_'+i" :value="t.value" :label="t.label" />
                </el-select>
                <!-- <el-select v-model="searchForm.action" placeholder="请选择处置措施">
                  <el-option value="采集信息" label="采集信息" />
                  <el-option value="滞留审查" label="滞留审查" />
                  <el-option value="立即抓捕" label="立即抓捕" />
                  <el-option value="如果是本人，则正常放行" label="如果是本人，则正常放行" />
                  <el-option value="如果不是本人，则正常放行" label="如果不是本人，则正常放行" />
                  <el-option value="如果是本人立即抓捕，否则采集信息" label="如果是本人立即抓捕，否则采集信息" />
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :span="6" label="布控状态" prop="status">
                <el-select v-model="searchForm.status" placeholder="请选择布控状态">
                  <el-option v-for="(t,i) in store.state.dictionary.bkStatus" :key="'status_'+i" :value="t.value" :label="t.label" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <template #toolsRight>
        <el-button type="primary" @click="showAddUser">
          新增
        </el-button>
      </template>
    </table-form>
    <dialog-form v-model="controlForm.visible" :title="controlForm.id ? '布控编辑' : '新增布控'" :confirm="handleSubmit">
      <el-form :model="controlForm" ref="form" label-width="140px" :rules="controlFormRules">
        <el-form-item label="姓名：" class="w50" prop="name">
          <el-input v-model="controlForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="车牌号/证件号：" class="w50" prop="num">
          <el-input v-model="controlForm.num" placeholder="请输入车牌号/证件号" />
        </el-form-item>
        <el-form-item label="布控类型：" class="w50" prop="type">
          <el-select v-model="controlForm.type" placeholder="请选择布控类型">
            <el-option value="person" label="人员布控" />
            <el-option value="car" label="车辆布控" />
          </el-select>
        </el-form-item>
        <el-form-item label="布控原因：" class="w50" prop="reason">
          <el-input v-model="controlForm.reason" placeholder="请输入布控原因" />
        </el-form-item>
        <el-form-item label="布控有效期开始时间：" class="w50" prop="startTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="controlForm.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="布控有效期结束时间：" class="w50" prop="endTime">
          <el-date-picker
            placeholder="开始时间"
            type="datetime"
            v-model="controlForm.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="处置措施：" class="w50" prop="action">
          <el-select v-model="controlForm.action" placeholder="请选择处置措施">
            <el-option value="采集信息" label="采集信息" />
            <el-option value="滞留审查" label="滞留审查" />
            <el-option value="立即抓捕" label="立即抓捕" />
            <el-option value="如果是本人，则正常放行" label="如果是本人，则正常放行" />
            <el-option value="如果不是本人，则正常放行" label="如果不是本人，则正常放行" />
            <el-option value="如果是本人立即抓捕，否则采集信息" label="如果是本人立即抓捕，否则采集信息" />
          </el-select>
        </el-form-item>
        <el-form-item label="布控范围：" class="w50" prop="areaCode">
          <el-cascader
            :options="store.getters.getAreaList"
            v-model="currentArea"
            :props="{
              checkStrictly: true,
              value: 'code',
              label: 'name'
            }"
            placeholder="请选择组织机构"
            clearable
            @change="changeOrgan"
          />
        </el-form-item>
        <el-form-item label="布控阈值：" class="w50" prop="faceYz">
          <el-input v-model="controlForm.faceYz" placeholder="请输入布控阈值" />
        </el-form-item>
        <el-form-item label="布控照片" class="w50" prop="img">
          <UploadFile ref="uploadFile" v-model="controlForm.img" :len="1" accept="img" />
        </el-form-item>
      </el-form>
    </dialog-form>
    <dialog-form v-model="controlForm.detailVisible" title="布控详情">
      <el-form :model="controlForm" ref="form" label-width="140px">
        <el-form-item label="姓名：" class="w50" prop="name">
          {{ controlForm.name }}
        </el-form-item>
        <el-form-item label="车牌号/证件号：" class="w50" prop="num">
          {{ controlForm.num }}
        </el-form-item>
        <el-form-item label="布控类型：" class="w50" prop="type">
          {{ typeList[controlForm.type] }}
        </el-form-item>
        <el-form-item label="布控原因：" class="w50" prop="reason">
          {{ controlForm.reason }}
        </el-form-item>
        <el-form-item label="布控有效期开始时间：" class="w50" prop="startTime">
          {{ controlForm.startTime }}
        </el-form-item>
        <el-form-item label="布控有效期结束时间：" class="w50" prop="endTime">
          {{ controlForm.endTime }}
        </el-form-item>
        <el-form-item label="处置措施：" class="w50" prop="action">
          {{ controlForm.action }}
        </el-form-item>
        <el-form-item label="布控范围：" class="w50" prop="areaCode">
          {{ store.state.areaList.find(t => t.code===controlForm.areaCode)?.name }}
        </el-form-item>
        <el-form-item label="布控阈值：" class="w50" prop="faceYz">
          {{ controlForm.faceYz }}
        </el-form-item>
        <el-form-item label="布控照片" class="w50" prop="img">
          <!-- <UploadFile accept="img" ref="uploadFile" disabled /> -->
          <img :src="controlForm.img">]
        </el-form-item>
      </el-form>
    </dialog-form>
  </div>
</template>
<script lang="ts" setup>
import {
  MenuProps,
  TableColumnsProps
} from '@/components/Table/types/tableForm'
import { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import { addControl, editControl, getControlList, delControl, detailControl, cancelControl } from '@/api/control'
import moment from 'moment'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'

// useStore
const store = useStore()
// 常量
const getInitialData = () => ({
  searchForm: {
    type: 'person',
    status: '1',
    startTime: moment().subtract(1, 'month').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: moment().format('YYYY-MM-DD 23:59:59'),
    action: '',
    num: ''
  },
  columnsPerson: [{
    prop: 'img',
    label: '头像',
    img: true
  }, {
    prop: 'name',
    label: '姓名'
  }, {
    prop: 'num',
    label: '证件号'
  }, {
    prop: 'type',
    label: '布控类型',
    formatter: (row) => {
      return typeList[row.type]
    }
  }, {
    prop: 'reason',
    label: '布控原因'
  }, {
    prop: 'action',
    label: '处置措施',
    formatter: (row) => {
      return store.state.dictionaryMap.action[row.action]
    }
  }, {
    prop: 'startTime',
    label: '布控开始时间'
  }, {
    prop: 'endTime',
    label: '布控结束时间'
  }, {
    prop: 'status',
    label: '布控状态',
    formatter: (row) => {
      return statusList[row.status]
    }
  }] as TableColumnsProps[],
  columnsCar: [{
    prop: 'num',
    label: '车牌号'
  }, {
    prop: 'type',
    label: '布控类型',
    formatter: (row) => {
      return typeList[row.type]
    }
  }, {
    prop: 'reason',
    label: '布控原因'
  }, {
    prop: 'action',
    label: '处置措施'
  }, {
    prop: 'startTime',
    label: '布控开始时间'
  }, {
    prop: 'endTime',
    label: '布控结束时间'
  }, {
    prop: 'status',
    label: '布控状态',
    formatter: (row) => {
      return store.state.dictionaryMap.bkStatus[row.status]
    }
  }] as TableColumnsProps[],
  columns: [] as TableColumnsProps[],
  menus: [{
    name: '详情',
    event: 'detail',
    type: 'primary'
  }, {
    name: '编辑',
    event: 'edit',
    type: 'primary',
    visible: row => row.status !== 2
  }, {
    name: '删除',
    event: 'del',
    type: 'danger',
    visible: row => row.status !== 2 && row.status !== 4
  }, {
    name: '撤销',
    event: 'cancel',
    type: 'info',
    visible: row => row.status !== 1
  }] as MenuProps[],
  controlForm: {
    id: 0,
    name: '',
    type: 'person',
    num: '',
    reason: '',
    action: '',
    img: '',
    startTime: '',
    endTime: '',
    areaCode: '',
    faceYz: '',
    visible: false,
    detailVisible: false
  },
  controlFormRules: {
    type: [{ required: true, message: '请选择布控类型', trigger: 'change' }],
    num: [{ required: true, message: '请输入证件号/车牌号', trigger: 'change' }],
    action: [{ required: true, message: '请选择处置措施', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择布控开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择布控结束时间', trigger: 'change' }],
    areaCode: [{ required: true, message: '请选择布控范围', trigger: 'change' }]
  } as IFormRule,
  // 绑定搜索栏级联树
  currentArea: [] as any
})
// 布控类型
const typeList = {
  person: '人证布控',
  face: '人脸布控',
  car: '车辆布控'
}
// 审批状态
const statusList = {
  1: '布控中',
  2: '保存',
  3: '布控审批中',
  4: '已撤销',
  5: '撤销审批中',
  99: '已过期'
}
// 表头
const columns = ref(getInitialData().columns)
const columnsPerson = ref(getInitialData().columnsPerson)
const columnsCar = ref(getInitialData().columnsCar)
// 搜索条件
const searchForm = ref(getInitialData().searchForm)
// 操作栏
const menus = ref(getInitialData().menus)
// 查询数据列表
const load = async (form: any = {}) => getControlList(form)
// 表单
const controlForm = ref(getInitialData().controlForm)
const form = ref<IElForm>()
// 表单校验
const controlFormRules = ref(getInitialData().controlFormRules)
// 搜索框的级联选择器绑定参数
const currentArea = ref(getInitialData().currentArea)
// 搜索栏级联选择框选择后将对应值赋值到searchForm中
const changeOrgan = () => {
  controlForm.value.areaCode = currentArea.value[currentArea.value.length - 1]
}
// 上传图片
const uploadFile = ref()
// 新增
const router = useRouter()
const showAddUser = () => {
  Object.assign(controlForm.value, getInitialData().controlForm)
  Object.assign(currentArea.value, getInitialData().currentArea)
  router.push({
    path: 'dispatchInfo'
  })
  // controlForm.value.visible = true
  // nextTick(() => {
  //   form.value?.clearValidate()
  //   uploadFile.value.setFiles([])
  // })
}
// 操作栏事件
const tableEvent = async (event: MenuProps['event'], row: any) => {
  const data = await detailControl(row.id)
  switch (event) {
    // 详情
    case 'detail':
      Object.assign(controlForm.value, data)
      currentArea.value = controlForm.value.areaCode
      router.push({
        path: 'dispatchInfo',
        query: {
          data: JSON.stringify(data),
          type: 'detail'
        }
      })
      break
    // 编辑
    case 'edit':
      Object.assign(controlForm.value, row)
      currentArea.value = controlForm.value.areaCode
      router.push({
        path: 'dispatchInfo',
        query: {
          data: JSON.stringify(data),
          type: 'edit'
        }
      })
      break
    // 删除
    case 'del':
      ElMessageBox({
        title: '提示',
        message: `确定删除【${row.name}】布控？`,
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        center: true
      }).then(async () => {
        await delControl(row.id)
        ElMessage.success('删除成功')
        table.value.fetchData()
      })
      break
    // 撤销
    case 'cancel':
      ElMessageBox.prompt(`确定要撤销【${row.name}】布控么？`, '提示', {
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        center: true,
        inputValidator: (value) => Boolean(value),
        inputErrorMessage: '撤销原因不能为空',
        inputPlaceholder: '请输入撤销原因'
      }).then(async ({ value }) => {
        await cancelControl(row.id, value)
        ElMessage.success('撤销成功')
        table.value.fetchData()
      })
      break
    // 预警下发
    case 'xiafa':

      break
  }
}
// 提交事件
const table = ref()
const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) return
  const params = controlForm.value
  const avatar = uploadFile.value.getFiles()
  const data = {
    name: params.name,
    type: params.type,
    num: params.num,
    reason: params.reason,
    action: params.action,
    img: avatar.src || '',
    startTime: params.startTime,
    endTime: params.endTime,
    areaCode: params.areaCode,
    faceYz: params.faceYz
  }
  if (params.id) {
    await editControl(params)
    ElMessage.success('修改成功')
  } else {
    await addControl(data)
    ElMessage.success('新增成功')
  }
  controlForm.value.visible = false
  table.value.fetchData()
}

const changeType = (val: any) => {
  columns.value = getInitialData().columns
  // Object.assign(columns.value, getInitialData().columns)
  if (val === 'car') {
    columns.value.push(...columnsCar.value)
  } else {
    columns.value.push(...columnsPerson.value)
  }
  table.value.fetchData()
}

onMounted(() => {
  columns.value.push(...columnsPerson.value)
})
</script>

<style lang="scss" scoped>
  .state {
    width: 100%;
    height: 80px;
    border: 1px solid #ccc;
    margin-right: 1%;
    display: flex;
    flex-flow: row nowrap;
    .content1 {
      width: 75%;
      height: 100%;
      display: flex;
      flex-flow: column nowrap;
      > div {
        width: 98%;
        margin-right: 10%;
        &:first-child {
          line-height: 40px;
          font-size: 24px;
          color: #666666;
          border-bottom: 1px solid #999999;
        }
        &:nth-child(2) {
          margin-top: 10px;
          line-height: 30px;
          font-size: 12px;
          color: #999999;
        }
      }
    }
    &:first-child {
      .color {
        width: 3%;
        height: 100%;
        background: red;
      }
      .image {
        width: 22%;
        height: 100%;
        background: url("../../assets/control/czrk.png") no-repeat;
        background-size: 80% 40%;
        background-position: 30% 20%;
      }
    }
    &:nth-child(2) {
      .color {
        width: 3%;
        height: 100%;
        background: blue;
      }
      .image {
        width: 25%;
        height: 100%;
        background: url("../../assets/control/ldrk.png") no-repeat;
        background-size: 80% 40%;
        background-position: 30% 20%;
      }
    }
  }
</style>
